/**
 * 
 */
package com.td.framework.webmanager.yhz.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.td.framework.common.Constant;
import com.td.framework.utils.DateUtils;
import com.td.framework.webmanager.domain.AppsysYhz;
import com.td.framework.webmanager.yhz.dao.YhzDao;

/**
 * 
 * Title: 用户组数据层实现类 Description: 实现数据层用户组处理方法 Copyright: Copyright (c) 2008
 * Company 北京水软科技有限公司
 * 
 * @author FLT006
 * @version 1.0
 */
public class YhzDaoImpl extends HibernateDaoSupport implements YhzDao {
	private static final Log log = LogFactory.getLog(YhzDaoImpl.class);
	private String sql = "";// sql语句;
	private List<AppsysYhz> yhzList = null;// 用户组list;
	private boolean delStatus;// 删除记录标志 true:彻底删除；false:象征性删除;
	private boolean flag = false;// 操作状态;

	/**
	 * @toDo:保存用户组信息;
	 * @param appsysYhz
	 * @return boolean;
	 */
	public boolean addAppsysYhz(AppsysYhz appsysYhz) {
		// TODO Auto-generated method stub
		try {
			if (appsysYhz != null) {
				appsysYhz.setScbz(new Long(0));
				if (appsysYhz.getCjr() == null) {
					appsysYhz.setCjr("admin");
				}
				appsysYhz.setYhzlx(new Long(0));
				appsysYhz.setCjrq(DateUtils.currentDate());
				appsysYhz.setXtbm(Constant.SYS_XTBM);
				this.getHibernateTemplate().save(appsysYhz);
				flag = true;
			}
		} catch (RuntimeException re) {
			flag = false;
			log.error("Exception： YhzDaoImpl+addAppsysYhz", re);
			throw re;
		}
		return flag;
	}

	/**
	 * @toDo:删除用户组信息,支持批量删除;
	 * @param yhzbhs
	 * @return boolean;
	 */
	public boolean deleteAppsysYhz(String[] yhzbhs) {
		// TODO Auto-generated method stub
		sql = "update appsys_yhz t set t.scbz=1 where 1=1 and ";
		if (delStatus) {
			sql = "delete from appsys_yhz t  where 1=1 and ";
		}
		String condition = " t.yhzbh in ( ";// 删除条件;
		for (int i = 0; i < yhzbhs.length; i++) {
			if (i == yhzbhs.length - 1) {
				condition += yhzbhs[i] + " ) ";
			} else {
				condition += yhzbhs[i] + ", ";
			}

		}
		sql += condition;
		try {
			Connection con = this.getSession().connection();
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.executeUpdate();
			pstmt.close();
			con.close();
			flag = true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			flag = false;
			log.error("Exception： YhzDaoImpl+deleteAppsysYhz", e);
		}
		return flag;
	}

	/**
	 * @toDo:通过用户组名称属性查询用户组列表;
	 * @param pageSize
	 * @param startRow
	 * @return list;
	 */
	@SuppressWarnings("unchecked")
	public List<AppsysYhz> findByYhzm(int pageSize, int startRow) {
		Session session = getSession();
		Query query = session.createQuery(sql);
		query.setFirstResult(startRow);
		query.setMaxResults(pageSize);
		yhzList = query.list();
		//session.close();
		return yhzList;
	}

	/**
	 * @toDo:得到总记录数;
	 * @return rows;
	 */
	@SuppressWarnings("unchecked")
	public int getRows() {
		int rows = 0;
		List list = this.getHibernateTemplate().find(sql);
		rows = list.size();
		return rows;
	}

	/**
	 * @toDo:通过用户编号查询所属用户组
	 * @param yhbh
	 * @param flag 0所属用户组,1系统用户组
	 * @return list;
	 */
	@SuppressWarnings("unchecked")
	public List<AppsysYhz> findByYhbh(String yhbh,int flag) {
		sql = " from com.td.framework.webmanager.domain.AppsysYhz t "
				+ "where t.scbz=0 and t.yhzlx=0 and t.xtbm = '"+Constant.SYS_XTBM+"' and t.yhzbh in "
				+ "(select a.yhbhz from com.td.framework."
				+ "webmanager.domain.AppsysYhyhzgx a where a.scbz=0 and a.yhbh='"
				+ yhbh + "')  order by t.yhzbh ";
		if(flag==1)
		{
			sql = " from com.td.framework.webmanager.domain.AppsysYhz t "
				+ "where t.scbz=0 and t.yhzlx=0 and t.xtbm = '"+Constant.SYS_XTBM+"' and t.yhzbh not in "
				+ "(select a.yhbhz from com.td.framework."
				+ "webmanager.domain.AppsysYhyhzgx a where a.scbz=0 and a.yhbh='"
				+ yhbh + "')  order by t.yhzbh ";
		}
		yhzList = this.getHibernateTemplate().find(sql);
		return yhzList;
	}

	/**
	 * @toDo:通过用户组编号(主键)查询用户组;
	 * @param yhzbh
	 * @return appsysYhz;
	 */
	public AppsysYhz getAppsysYhz(Long yhzbh) {
		// TODO Auto-generated method stub
		AppsysYhz appsysYhz = (AppsysYhz) this.getHibernateTemplate().get(
				AppsysYhz.class, yhzbh);
		return appsysYhz;
	}

	/**
	 * @toDo:更新用户组信息;
	 * @param appysysYhz
	 * @return boolean;
	 */
	public boolean updateAppsysYhz(AppsysYhz appsysYhz) {
		// TODO Auto-generated method stub
		try {
			appsysYhz.setYhzlx(new Long(0));
			this.getHibernateTemplate().update(appsysYhz);
			flag = true;
		} catch (RuntimeException re) {
			flag = false;
			log.error("Exception： YhzDaoImpl+updateAppsysYhz", re);
			throw re;
		}
		return flag;
	}

	/**
	 * @toDo:保存用户用户组关系;
	 * @param yhbhs
	 * @param yhzbhs
	 * @param addFlag
	 *            数据添加区分,0为用户选择用户组,1为用户组选择用户
	 * @return boolean;
	 */
	public boolean addAppsysYhYhzGx(String yhbhs, String yhzbhs, int addFlag) {
		Connection con = null;
		Session session = getSession();
		try {
			con = session.connection();
			Statement st = con.createStatement();
			con.setAutoCommit(false);
			// 用户选择用户组
			if (addFlag == 0) {
				// 删除原有关联关系
				sql = "delete from appsys_yhyhzgx where yhbh='" + yhbhs+"' ";
				st.addBatch(sql);
				if (!yhzbhs.trim().equals("") && !yhzbhs.trim().equals("null")) {
					// 插入新数据
					for (int i = 0; i < yhzbhs.split(",").length; i++) {
						sql = "insert into appsys_yhyhzgx (yhbh,yhbhz,scbz) "
								+ "values ('"
								+ yhbhs
								+ "'," + yhzbhs.split(",")[i].trim() + ",0)";
						st.addBatch(sql);
					}

				}
			}
			// 用户组选择用户
			else {
				// 删除原有关联关系
				sql = "delete from appsys_yhyhzgx where yhbhz=" + yhzbhs;
				st.addBatch(sql);
				if (!yhbhs.trim().equals("") && !yhbhs.trim().equals("null")) {
					// 插入新数据
					for (int i = 0; i < yhbhs.split(",").length; i++) {
						sql = "insert into appsys_yhyhzgx (yhbh,yhbhz,scbz) "
								+ "values ('"
								+ yhbhs.split(",")[i].trim() + "'," + yhzbhs + ",0)";
						st.addBatch(sql);
					}

				}
			}
			st.executeBatch();
			con.commit();
			flag = true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			flag = false;
			e.printStackTrace();
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				log.error("Exception： YhzDaoImpl+addAppsysYhYhzGx", e);
			}
		} finally {

			try {
				if (con != null) {
					con.close();
				}
				//session.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				flag = false;
				log.error("Exception： YhzDaoImpl+addAppsysYhYhzGx", e);
			}

		}
		return flag;
	}

	/**
	 * @toDo:验证用户名是否存在;
	 * @param yhbh
	 * @param yhm
	 * @return boolean;
	 */
	@SuppressWarnings("unchecked")
	public boolean checkYhm(String yhzbh, String yhzm) {
		boolean flag = false;
		sql = " from com.td.framework.webmanager.domain.AppsysYhz t "
				+ "where t.scbz=0 and t.yhzlx=0 and t.yhzm ='"+yhzm.trim()+"' ";
		if(!yhzbh.equals("")&&!yhzbh.equals("null"))
		{
			sql +=" and t.yhzbh!="+yhzbh;
		}
		yhzList = this.getHibernateTemplate().find(sql);
		if(!yhzList.isEmpty())
		{
			flag = true;
		}
		return flag;
	}

	/**
	 * @toDo:get删除记录标志 ;
	 * @return the delStatus
	 */
	public boolean isDelStatus() {
		return delStatus;
	}

	/**
	 * @toDo:set删除记录标志 ;
	 * @param delStatus
	 *            the delStatus to set
	 */
	public void setDelStatus(boolean delStatus) {
		this.delStatus = delStatus;
	}

	/**
	 * @toDo:get查询语句;
	 * @return the sql
	 */
	public String getSql() {
		return sql;
	}

	/**
	 * @toDo:set查询语句;
	 * @param sql
	 *            the sql to set
	 */
	public void setSql(String yhzm) {
		sql = " from com.td.framework.webmanager.domain.AppsysYhz t "
				+ "where t.scbz=0 and t.yhzlx=0 and t.xtbm = '"+Constant.SYS_XTBM+"'  order by t.yhzbh ";
		if (!yhzm.trim().equals("") && !yhzm.trim().equals("null")) {
			sql = " from com.td.framework.webmanager.domain.AppsysYhz t "
					+ "where t.scbz=0 and t.yhzlx=0 and t.xtbm = '"+Constant.SYS_XTBM+"' " +
							" and t.yhzm like '%" + yhzm
					+ "%' order by t.yhzbh ";
		}

	}
	
	/**
	 * 检验用户组名称是否相同
	 * @param String 如果是多个值的话用，隔开 
	 * @return  boolean
	 */
	public boolean checkName(String name){
		boolean flag = true;
		String sql = "select count(*)from appsys_yhz where  yhzm ='"+name+"'";
		String result = this.getSessionFactory().getCurrentSession().createSQLQuery(sql).uniqueResult().toString();
		if("0".equals(result)){
			flag =false;
		}
		return flag;
	}

}
